<?php

require_once('publiccontroller.php');

// Gestion de l'espace candidat dans le front office
class Candidat extends PublicController
{
	function Candidat()
	{
		parent::PublicController();
		$this->set_page_title('Espace candidat');
		$this->load->helper('html');
		$this->load->helper('form');
		$this->load->helper('cookie');

		$this->load->model('User');
		$this->load->model('UserStatus');

		$this->data = array();

		// Paramètres des éléments du formulaire à générer
		$this->data['form_action'] = 'candidat/connection';
		$this->data['form_attr'] = array('class' => '');
		$this->data['input'] = array('id' => 'email', 'name' => 'email', 'size' => '30');
		$this->data['password'] = array('id' => 'password', 'name' => 'password', 'size' => '30');
		$this->data['submit'] = array('name' => 'connect', 'value' => 'Connexion');
	}


	/**
	 * Formulaire de connexion à l'espace
	 */
	function index()
	{
		if ($this->is_candidat_connected()) {
			redirect('/candidat/espace');
		}

		$this->data['notice'] = 'Cette section est reservée aux candidats ayant complété le formulaire d\'inscription';
		$this->data['notice_type'] = 'info';
		$this->data['email'] = '';
		$this->data['remember_me'] = 0;
		$this->_display('candidat_login', $this->data);
	}

	/**
	 * Formulaire de regénération de mot de passe
	 */
	function password()
	{
		if ($this->is_candidat_connected()) {
			redirect('/candidat/espace');
		}

		$this->data['form_action'] = 'candidat/sendpass';
		$this->data['submit'] = array('name' => 'sendpass', 'value' => 'Envoyer');
		$this->data['email'] = '';
		$this->_display('candidat_password', $this->data);
	}


	function sendpass()
	{
		$this->load->model('User');
		
		$this->data['form_action'] = 'candidat/sendpass';
		$this->data['submit'] = array('name' => 'sendpass', 'value' => 'Envoyer');
		
		$email = isset($_POST['email']) ? $this->input->post('email') : null;
		$security_code_ok = $this->input->post('check_security_code') == $this->input->post('user_security_code');
		$errors = array();
		if (!check_email($email)) $errors[] = 'L\'e-mail saisi est invalide ou ne correspond à aucune candidature';
		if (!$security_code_ok) $errors[] = "Le code de sécurité n'est pas bon";
		
		if (!count($errors)) {
			$this->load->library('email');
			
			$this->email->from($email);
			$this->email->to(CONTACT_EMAIL);
			$this->email->subject('Site Miage : message de '.$name);
			$this->email->message($message);

			$this->data['email'] = '';
			if ($this->email->send()) {
				$this->data['notice'] = 'Un email contenant votre nouveau mot de passe vient d\'être envoyé à l\'adresse spécifiée !';
				$this->data['notice_type'] = 'success';
			}
			else {
				$this->data['notice'] = 'L\'email saisi est invalide ou ne correspond à aucune candidature';
				$this->data['notice_type'] = 'error';
			}
		}
		else {
			$this->data['email'] = $email;
			$this->data['notice'] = $errors;
			$this->data['notice_type'] = 'error';
		}
		
		$this->_display('candidat_password', $this->data);
	}

	function connection()
	{
		$email = $this->input->post('email');
		$crypted_password = crypt_password($this->input->post('password'));

		if ($this->connect_candidat($email, $crypted_password)) {
			// cookie management
			if ($this->input->post('remember_me')) {
				set_cookie('login', $email, '31536000');
				set_cookie('password', $crypted_password, '31536000');
			}
			else {
				delete_cookie('login');
				delete_cookie('password');
			}
			redirect('/candidat/espace');
		}
		else {
			$this->data['notice'] = 'Erreur d\'authentification';
			$this->data['notice_type'] = 'error';
			$this->data['email'] = $this->input->post('email');
			$this->data['remember_me'] = $this->input->post('remember_me');
			$this->_display('candidat_login', $this->data);
		}
	}

	function disconnect()
	{
		$this->session->sess_destroy();
		$this->session->set_userdata('candidat_connect', FALSE);
		delete_cookie('login');
		delete_cookie('password');

		redirect('/candidat');
	}

	function espace($data = array())
	{
		$this->restraint_access();

		$candidat = new User();
		$candidat->id = $this->session->userdata('user_id');
		$candidat->email = $this->session->userdata('email');
		$candidat->name = $this->session->userdata('name');
		$candidat->firstname = $this->session->userdata('firstname');
		$candidat->status_id = $this->User->get_status_id($candidat->id);

		$candidat_status = $this->UserStatus->get_by_id($candidat->status_id);
		$candidat_status_history = $this->User->get_status_history($candidat->id);

		$data['name'] = $candidat->name;
		$data['firstname'] = $candidat->firstname;
		$data['status_code'] = $candidat_status->code;
		$data['status_label'] =  $candidat_status->label;
		$data['status_history'] = $candidat_status_history;
		$data['link_disconnect'] = 'candidat/disconnect';
		$data['link_download'] = 'candidat/dlpdf';
		$data['link_demission'] = 'candidat/demission';
		$data['link_demission_id'] = $candidat_status->code == 'resignation' ? 'demission_disabled' : 'demission_button';

		$this->_display('candidat_espace', $data);
	}


	function dlpdf()
	{
		$this->restraint_access();

		$this->load->plugin('dompdf');

		// preparation of pdf-needed data
		/* session */
		$data['name'] = $this->session->userdata('name');
		$data['firstname'] = $this->session->userdata('firstname');
		$data['email'] = $this->session->userdata('email');

		/* database */
		$this->load->model('Insc');
		$user_fields = $this->Insc->insc_entry_get_by_user_id($this->session->userdata('user_id'));

		foreach($user_fields as $field) {
			$val_field = 'value_'.$field->field_type;
			$data[$field->field_id] = $field->$val_field;
		}

		// retrieving html from view template
		$html = $this->load->view('public/candidat/pdf_template', $data, TRUE); // récupère la view en tant que chaîne

		// PDF stream (direct download)
		streampdf($html, strtolower($data['firstname'].'_'.$data['name']));
	}


	function demission()
	{
		$this->restraint_access();

		if($this->User->get_status_id($this->session->userdata('user_id')) != $this->UserStatus->get_id_by_code('resignation')) {
			$candidat = new User();
			$candidat->id = $this->session->userdata('user_id');
			$candidat->email = $this->session->userdata('email');
			$candidat->name = $this->session->userdata('name');
			$candidat->firstname = $this->session->userdata('firstname');
			$candidat->status_id = $this->User->get_status_id($candidat->id);

			$this->User->set_status_from_code($candidat, 'resignation', $candidat->id);
			$this->User->save_status_id($candidat);

			$data['notice'] = 'Votre démission a bien été enregistrée';
			$data['notice_type'] = 'success';
		}
		else {
			$data['notice'] = 'Votre démission a déjà été enregistrée';
			$data['notice_type'] = 'error';
		}
		$this->espace($data);
	}

	/**
	 * Connecter le candidat
	 * @return true si connexion réussie
	 */
	private function connect_candidat($email, $crypted_password)
	{
		$user = new User();
		$user->email = $email;
		$user->password = $crypted_password;
		$user->last_used_ip = $this->input->ip_address();

		if (($user = $user->connect()) && !in_array($user->status_code, array('admin','former_student'))) {
			$sess = array(
				'admin_connect' => FALSE,
				'candidat_connect' => TRUE,
				'user_id' => $user->id,
				'email' => $user->email,
				'name' => $user->name,
				'firstname' => $user->firstname
			);
			$this->session->set_userdata($sess);
			return true;
		}
		$this->session->set_userdata('candidat_connect', FALSE);
		return false;
	}

	private function is_candidat_connected()
	{
		// si déjà connecté
		if ($this->session->userdata('candidat_connect')) {
			return true;
		}
		// sinon, tentative de connexion par cookie
		$email = $this->input->cookie('login');
		$crypted_password = $this->input->cookie('password');
		if ($this->connect_candidat($email, $crypted_password)) {
			return true;
		}
		return false;
	}

	/**
	 * Tenter d'accéder à l'espace candidat
	 * @return true si accès autorisé
	 */
	private function restraint_access()
	{
		if (!$this->is_candidat_connected()) {
			// houste !
			redirect('/candidat');
		}
	}

}
